import React, {Component} from 'react';
import {
    ActivityIndicator,
    View,
    StyleSheet,
    Dimensions,
    Picker,
    Slider,
    Text,
    Switch,
    WebView,
    Button,
    TouchableOpacity,
    Alert,
    ToastAndroid,
    AsyncStorage,
    Image,
    DatePickerAndroid,
    TimePickerAndroid, Keyboard, TextInput, NetInfo, PermissionsAndroid, ScrollView
} from "react-native";
import XPay from 'react-native-puti-pay'
import px2dp from "./px2dp";
import {Toast} from "native-base";
import Platform from "./js/Platform";
import AppState from "./js/AppState";
import Geolocation from 'Geolocation'
import TestAntDesignActionSheet from "./js/antDesign/TestAntDesignActionSheet";

export default class more extends Component {
    constructor(props) {
        super(props);
        // this.state = {
        //     isFirstLoad: true,
        //     mapRegion: undefined,
        //     mapRegionInput: undefined,
        //     annotations: []
        // }
        this.state = {
            language: 'JAVA',
            slideValue: 5,
            isOn: false,
            netContent: '网络请求得到的内容',
            keyboardText: '键盘收回',
            connectionInfo: '',
            permission: PermissionsAndroid.PERMISSIONS.CAMERA,
            hasPermission: 'Not Checked'
        }
    }

    componentWillMount() {
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
                this.setState({
                    keyboardText: '键盘弹出'
                });
            }
        );
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
                this.setState({
                    keyboardText: '键盘收回'
                });
            }
        );
        NetInfo.addEventListener('connectionChange', (connectionInfo) => {
            this.setState({connectionInfo: connectionInfo})
        });
        NetInfo.fetch().done((connectionInfo) => {
            this.setState({connectionInfo: connectionInfo});
        })
    }

    componentWillUnmount() {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
    }

    render() {
        // if(Platform.OS === 'ios'){
        //  return null;
        // }else {
        //     return(
        //         <View style={styles.container}></View>
        //     );
        // }
        return (
            //加载进度圆圈
            // {
            //     /*<View style={styles.container}>*/
            //     /*<ActivityIndicator color='purple' size='large'/>*/
            //     /*</View>*/
            // }
            <View style={styles.container}>
                <ScrollView keyboardShouldPersistTaps={"handled"}>
                    {/*//地图组件(只在ios平台有效 可以用三方组件 react-native-map替代，且性能更好*/}
                    {/*<MapView style={styles.map}>*/}
                    {/*onRegionChange={this._onRegionChange.bind(this)}*/}
                    {/*onRegionChangeComplete={this._RegionChangeComplete.bind(this)}*/}
                    {/*region={this.state.region}*/}
                    {/*annotations={this.state.annotations}*/}
                    {/*</MapView>*/}
                    {/*//选择器组件*/}
                    <Picker style={styles.picker} selectedValue={this.state.language}
                            onValueChange={(lang) => this.setState({language: lang})}

                    >
                        <Picker.Item label='Java' value='java'/>
                        <Picker.Item label='JavaScript' value='javascript'/>
                    </Picker>
                    {/*//选择范围组件*/}
                    <Slider style={{width: 200}}
                            minimumValue={0}
                            step={1}
                        //Slider滑道右侧的颜色
                            maximumTrackTintColor='red'
                        //Slider 滑道左侧的颜色
                            minimumTrackTintColor='blue'
                            maximumValue={10}//最大值
                            value={this.state.slideValue}//Slider滑块的初始位置
                            onValueChange={(value) => {
                                this.setState({slideValue: value})
                            }}

                    />
                    <Text>Slider值:{this.state.slideValue}</Text>
                    <Switch
                        //开启时的背景色
                        // onTintColor='blue'
                        //开关上圆形按钮的颜色
                        thumbColor='green'
                        //关闭时背景色
                        // tintColor='black'
                        onValueChange={() =>
                            this.setState({
                                isOn: !this.state.isOn//当状态值发生变化时回调
                            })
                        }
                        value={this.state.isOn === true}
                    />
                    {/*<WebView style={styles.web}*/}
                    {/*source={{uri:'https://www.baidu.com'}}/>*/}
                    <Button title={'支付宝支付'} onPress={this._pay.bind(this, 1)}/>
                    <TouchableOpacity onPress={this._pay.bind(this, 2)}>
                        <Text style={{marginTop: px2dp(15), backgroundColor: 'green', color: 'red'}}>
                            微信支付
                        </Text>
                    </TouchableOpacity>
                    <Button title={'网络数据请求'} onPress={this.getdataFromNet.bind(this)}>
                    </Button>
                    <Text>
                        {this.state.netContent}
                    </Text>
                    <TouchableOpacity onPress={() => {
                        this.props.navigation.navigate('animationExample')
                    }
                    }>
                        <Text>动画</Text>
                    </TouchableOpacity>
                    {/*<Image style={{width: Dimensions.get('window').width, height: px2dp(200)}}
                       source={require('./image/reba.jpg')}/>*/}
                    <Text>{Platform.systemName}</Text>
                    <AppState/>
                    <Button
                        style={{marginBottom: px2dp(5)}}
                        title='日期选择器' onPress={
                        this._showDatePicker
                    }/>
                    <Button title='时间选择器' onPress={
                        this._showTimePicker
                    }/>
                    <Button
                        style={{marginTop: px2dp(5)}}
                        title='选择位置' onPress={
                        () => {
                            Geolocation.getCurrentPosition(
                                (data) => {
                                    Alert.alert('获取位置成功', JSON.stringify(data))
                                }, () => {
                                    Alert.alert('获取位置失败', null, null);
                                }
                            );
                        }
                    }/>
                    <View>
                        <Text>{this.state.keyboardText}</Text>
                        <TextInput style={{
                            width: Dimensions.get('window').width,
                            height: 50,
                            backgroundColor: 'lightgray'
                        }
                        }/>
                    </View>
                    <Text>当前联网类型:{this.state.connectionInfo}</Text>
                    <Text>权限状态:{this.state.hasPermission}</Text>
                    <Button title='申请摄像头权限' onPress={this._requestCameraPermission
                    }/>
                    <Button title='RN与原生交互' onPress={() => {
                        this.props.navigation.navigate('rnConnectWithNative')
                    }
                    }/>
                    <Button title='从相册选取图片' onPress={() => {
                        this.props.navigation.navigate('imagePicker')
                    }
                    }/>
                    <Button title='调用原生组件' onPress={() => {
                        this.props.navigation.navigate('communication')
                    }
                    }/>
                    <Button title='web' onPress={() => {
                        this.props.navigation.navigate('web')
                    }
                    }/>
                    <Button title='test' onPress={() => {
                        this.props.navigation.navigate('test')
                    }
                    }/>
                    <Button title='bottomNavigator' onPress={() => {
                        this.props.navigation.navigate('navigation')
                    }
                    }/>
                    <Button title='switchNavigator' onPress={() => {
                        this.props.navigation.navigate('switchNavigator')
                    }
                    }/>
                    <Button title='Animated示例' onPress={() => {
                        this.props.navigation.navigate('AnimatedDemo')
                    }
                    }/>
                    <Button title='scrollableTab' onPress={() => {
                        this.props.navigation.navigate('ScrollableTab')
                    }
                    }/>
                    <Button title='scrollableTab2' onPress={() => {
                        this.props.navigation.navigate('ScrollableTab2')
                    }
                    }/>
                    <Button title='VpTest' accessibilityLabel='VpTest' onPress={() => {
                        this.props.navigation.navigate('vpTest')
                    }
                    }/>
                    <Button title='Ant Design' accessibilityLabel='Ant Design' onPress={() => {
                        this.props.navigation.navigate('TestAntDesign')
                    }
                    }/>
                    <Button title='Ant Design -TabBar' accessibilityLabel='Ant Design' onPress={() => {
                        this.props.navigation.navigate('TestAntDesiginTabBar')
                    }
                    }/>
                    <Button title='Ant Design -Button' accessibilityLabel='Ant Design' onPress={() => {
                        this.props.navigation.navigate('TestAntDesiginButton')
                    }
                    }/>
                    <Button title='Ant Design -CheckBox' accessibilityLabel='Ant Design' onPress={() => {
                        this.props.navigation.navigate('TestAntDesiginCheckBox')
                    }
                    }/>
                    <Button title='Ant Design -DatePicker' accessibilityLabel='Ant Design' onPress={() => {
                        this.props.navigation.navigate('TestAntDesignDatePicker')
                    }
                    }/>
                    <Button title='Ant Design -InputItem' accessibilityLabel='Ant Design' onPress={() => {
                        this.props.navigation.navigate('TestAntDesignInputItem')
                    }
                    }/>
                    <Button title='Ant Design -ActionSheet' accessibilityLabel='Ant Design' onPress={() => {
                        this.props.navigation.navigate('TestAntDesignActionSheet')
                    }
                    }/>
                    <Button title='Ant Design -Modal' accessibilityLabel='Ant Design' onPress={() => {
                        this.props.navigation.navigate('TestAntDesignModal')
                    }
                    }/>
                    <Button title='Ant Design -Toast' accessibilityLabel='Ant Design' onPress={() => {
                        this.props.navigation.navigate('TestAntDesignToast')
                    }
                    }/>

                </ScrollView>
            </View>

        );
    }

    _requestCameraPermission = async () => {
        let result = await PermissionsAndroid.request(this.state.permission, {
            title: '权限申请',
            message: '申请摄像头权限'
        });
        this.setState({hasPermission: result});
    }
    _showDatePicker = async () => {
        try {
            let newState = {};
            const {action, year, month, day} = await DatePickerAndroid.open();
            if (action === DatePickerAndroid.dismissedAction) {
                newState['dateText'] = '取消选择';
            } else {
                let date = new Date(year, month, day);
                newState['dateText'] = date.toLocaleDateString();
                console.log(newState.dateText);
                ToastAndroid.show(newState.dateText, 1000);
            }
        } catch ({code, message}) {
            console.log('打开DatePickerAndroid失败' + message);
        }
    }
    _showTimePicker = async () => {
        try {
            let newState = {};
            const {action, minute, hour} = await TimePickerAndroid.open();
            if (action === DatePickerAndroid.dismissedAction) {
                newState['timeText'] = '取消选择';
            } else {
                newState['timeText'] = hour + ':' + minute;
                ToastAndroid.show(newState.timeText, 1000);
            }
        } catch ({code, message}) {
            console.log('打开TimePickerAndroid失败' + message);
        }
    };

    /**
     * fetch和数据缓存
     */
    getdataFromNet() {
        const url = 'http://192.168.0.127:8092/base/user/getBalanceloglist?balanceType=1';
        fetch(url, {
            method: 'GET',
            headers: {
                'AccessToken': '38d0fd69aedc4fe1b566a4cf5b180932'
            }
        })
            .then((response) => response.json())
            .then((json) => {
                // Toast.show()
                if (json) {
                    this.setState({netContent: json.message});
                    AsyncStorage.setItem('response', JSON.stringify(json))
                }
            }).catch((error) => {
            AsyncStorage.getItem('response')
                .then((values) => {
                    this.setState({netContent: JSON.parse(values).message});
                });
            Toast.show('网络出错了')
        })
    }

    _pay(type) {
        switch (type) {
            case 1:
                // //支付宝支付
                let data = 'charset=utf-8&biz_content=%7B%22timeout_express%22%3A%2230m%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.01%22%2C%22subject%22%3A%221%22%2C%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%220104142836-3220%22%7D&method=alipay.trade.app.pay&app_id=2019010362728959&sign_type=RSA2&version=1.0&timestamp=2016-07-29+16%3A55%3A53&sign=dFH8p80psjjw2uJI9p0FoCRsb9RfEQ%2Fsp3vrnZ8V1OOTa1O2QD%2FZOdU8CoSDZa8LPmES%2FDz%2FzZr2z%2FNj7Q0j1RgIAobfdFDcnKZhuddLaziwuY8Vpwb%2BnTlkMDVfnek2SiCJ3wt3Kx%2FczisaBxneboMwLUOKLhfJA7bK8gqkAP1cwxaN5oBl0vgbVUJsRHMv1ixRZAZ414LvTEDAhD58GtPAwqRt4BacgMqNPLabiZTy%2F%2BDGNgIUePPq7S2bZ%2FVwvuyz1G1gXeZGNCumxkjFPJ46OZDFWSUpL5nxEIusR%2BfoAI3NwaNtE2fSkaoapaX9xmCsdyO1ZXiz2jGtkwfSlg%3D%3D';
                let orderInfo = "";
                XPay.alipay(data, this.aliPayResponse);
                // Alert.alert("支付宝支付")
                // ToastAndroid.show("支付宝支付", ToastAndroid.SHORT);
                break;
            case 2:
                //微信支付
                //设置微信ID
                XPay.setWxId('wxe1995edb06cd71ec')
                let params = {
                    partnerId: '001',
                    prepayId: '002',
                    packageValue: '哈哈',
                    nonceStr: '哈哈',
                    timeStamp: '哈哈',
                    sign: '哈哈',
                }
                XPay.wxPay(params, this.wechatPayResponse)
                //   Alert.alert("微信支付")
                //  ToastAndroid.show("微信支付", ToastAndroid.SHORT);
                break
        }
    }

    // _aliPay  () {
    //     console.log("点击进行支付");
    //     let data = 'partner=\"asdfasdf\"&seller_id=\"asdfasdf@qq.com\"&out_trade_no=\"ALIPAY15307684880120000000001\"&subject=\"描述\"&body=\"在线支付\"&total_fee=\"0.01\"&notify_url=\"http://xx.xx.xx.xx/api/0/alipay/alipayCallback\"&service=\"m.pay\"&payment_type=\"1\"&_input_charset=\"utf-8\"&it_b_pay=\"30m\"&sign=\sdfasdf\"&sign_type=\"RSA\"';
    //     Alipay.pay(data).then(function (data) {
    //         console.log(data);
    //     }, function (err) {
    //         console.log(err);
    //     });
    // }
    /**
     * 支付宝支付结果回调
     * @param response
     *
     */
    aliPayResponse = (response) => {
        let res = response;
        console.log(res);
        // console.log(res.json());
        console.log(res.resultStatus);
        if (res.resultStatus === '9000') {
            ToastAndroid.show('支付成功', ToastAndroid.SHORT)
        } else {
            // ToastAndroid.show('支付失败'+res.result.toString(), ToastAndroid.SHORT)
            // setTimeout(() => {
            //     Alert.alert(null, '支付失败' + res.result.toString() + res.memo);
            //     // ToastAndroid.showWithGravity('支付失败', ToastAndroid.SHORT,ToastAndroid.CENTER)
            // }, 100)
            Alert.alert(null, '支付失败' + res.result.toString() + res.memo);
        }
    }
    /**
     * 微信支付结果回调
     * @param response
     * 回调结果码 0:支付成功,
     *                          -1:原因：支付错误,可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
     *                          -2: 原因 用户取消,无需处理。发生场景：用户不支付了，点击取消，返回APP
     */
    wechatPayResponse = (response) => {
        let res = response;
        console.log(res);
        // console.log(res.json());
        // console.log(res.resultStatus);
        if (res.errCode === '0') {
            ToastAndroid.show('支付成功', ToastAndroid.SHORT)
        } else {
            Alert.alert(null, '支付失败');
            // ToastAndroid.show('支付失败'+res.result.toString(), ToastAndroid.SHORT)
            //Alert.alert(null, '支付失败')
            // setTimeout(() => {
            //     Alert.alert(null, '支付失败');
            //     // ToastAndroid.showWithGravity('支付失败', ToastAndroid.SHORT,ToastAndroid.CENTER)
            // }, 100)
            // ToastAndroid.showWithGravity('支付失败', ToastAndroid.SHORT,ToastAndroid.CENTER)
        }
    }
    // /**
    //  * 位置发生改变时的回调
    //  * @param region
    //  * @private
    //  */
    // _onRegionChange = (region) => {
    //     this.setState({mapRegionInput: region})
    // }
    //
    // _RegionChangeComplete = (region) => {
    //     this.setState({
    //         mapRegionInput: region,
    //         annotations: this._getAnnotations(region),
    //         isFirstLoad: false
    //     })
    // }
    //
    // _getAnnotations = (region) => {
    //     return [{
    //         longitude: region.longitude,
    //         latitude: region.latitude,
    //         title: '上海闵行区'
    //     }]
    // }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
    },
    map: {
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height
    },
    picker: {
        width: 150,
        height: 100
    },
    web: {
        width: Dimensions.get('window').width,
        height: 200
    }
})